package cn.jianyongjie.basic.controller;

import cn.jianyongjie.basic.utils.AjaxResult;
import cn.jianyongjie.basic.utils.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.plaf.multi.MultiPanelUI;
import java.io.IOException;

/**
* @Description: TODO
* @Author: JianYongJie
* @Version: 1.0
* @Date:  2022/5/5 9:36
*/
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /*
    * @Title: FastDfsController
    * @Description: 文件上传接口
    * @Author: JianYongJie
    * @Version: 1.0
    * @Date:  2022/5/5 9:42
    * @Parameters: * @param file
    * @Return cn.jianyongjie.basic.utils.AjaxResult
    */
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){

        // RequestParam此注解专门用来文件上传的

        try {
            // 获取文件扩展名
            String filename = file.getOriginalFilename();
            // 获取文件后缀名
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            // 调用工具类进行上传,返回路径
            String resultPath = FastdfsUtil.upload(file.getBytes(), extName);
            // 返回图片路径
            return AjaxResult.success().setResultObj(resultPath);
        }catch (IOException e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /*
    * @Title: FastDfsController
    * @Description: 删除图片
    * @Author: JianYongJie
    * @Version: 1.0
    * @Date:  2022/5/5 10:12
    * @Parameters: * @param path
    * @Return cn.jianyongjie.basic.utils.AjaxResult
    */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path",required = true) String path){

        try {
            String pathTmp = path.substring(1);
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }
}
